package com.xzhuang.task.quartz;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;

import net.sf.json.JSONObject;

import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;

import com.xzhuang.task.util.DBUtil;
import com.xzhuang.task.util.HttpUtil;
import com.xzhuang.task.util.HttpUtilX;
import com.xzhuang.task.util.QuartzUtil;

public class QuartzJobFactory implements Job {

	String desc = "";
	String[] param;

	public void execute(JobExecutionContext context) throws JobExecutionException {
		DBUtil db = new DBUtil();
		SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		ScheduleTask task = (ScheduleTask) context.getMergedJobDataMap().get("scheduleJob");
		String json = null;
		
		try {
			desc = task.getDescription();
			param = QuartzUtil.getExtendParam(desc);
			if (param[0].equals("1")) {// GET
//				json = HttpUtil.GET(task.getJobName());
				json = HttpUtilX.get(task.getJobName());
			} else {
//				json = HttpUtil.POST(task.getJobName());
				json = HttpUtilX.post(task.getJobName(), new HashMap<String,Object>());
			}
			if(null != json && json.length() > 0){
				if(QuartzUtil.isJsonFormat(json)){
					JSONObject myjson = JSONObject.fromObject(json);
					if(myjson != null && myjson.containsKey("success")){
						boolean isSuccess = myjson.getBoolean("success");
						if(!isSuccess){
							String str = myjson.containsKey("errorMsg") ? myjson.getString("errorMsg") : "";
							db.writeLog(format.format(new Date()), task.getJobName(), "http:" + param[0], str, 0);
							
						}
					}
					
					if(myjson != null && myjson.containsKey("result")){
						boolean isSuccess = myjson.getBoolean("result");
						if(!isSuccess){
							String str =  myjson.containsKey("message") ? myjson.getString("message") :"";
							db.writeLog(format.format(new Date()), task.getJobName(), "http:" + param[0], str, 0);
						}
					}	
				}
			}
		} catch (Exception e) {
			try {
				String msg = e.getMessage();
				msg = org.apache.commons.lang.exception.ExceptionUtils.getFullStackTrace(e);
				if (msg != null && msg.length() > 1500) {
					msg.substring(0, 1500);
				}
				db.writeLog(format.format(new Date()), task.getJobName(), "http:" + param[0], msg, 0);
			} catch (Exception se) {
				se.printStackTrace();
			}
		}

	}
}